# -*- coding: utf-8 -*-

from odoo import http
from odoo.http import request
import logging

from .main import api_response

_logger = logging.getLogger(__name__)


class ActivityItemController(http.Controller):
    
    @http.route('/api/v1/role-categories', type='http', auth='public', methods=['GET'], csrf=False, cors='*')
    def get_role_categories(self, **kwargs):
        """获取所有角色分类列表"""
        try:
            _logger.info('🔍 GET /role-categories')
            
            categories = request.env['item.role.category'].sudo().search([
                ('active', '=', True)
            ], order='sequence asc')
            
            result = []
            for cat in categories:
                result.append({
                    'id': cat.id,
                    'name': cat.name,
                    'sequence': cat.sequence,
                    'description': cat.description or '',
                })
            
            _logger.info(f'✅ 返回 {len(result)} 个角色分类')
            
            return request.make_json_response(api_response(True, result))
            
        except Exception as e:
            _logger.error(f'❌ 获取角色分类失败: {str(e)}', exc_info=True)
            return request.make_json_response(api_response(False, message=f'获取失败: {str(e)}'))
    
    @http.route('/api/v1/init/role-categories', type='http', auth='public', methods=['POST'], csrf=False, cors='*')
    def init_role_categories(self, **kwargs):
        """初始化默认角色分类（公开接口）"""
        try:
            _logger.info('🎯 POST /init/role-categories - 创建默认角色分类')
            
            categories = [
                {'name': '会议角色', 'sequence': 10, 'description': '主持人、计时官、总评官等会议组织角色'},
                {'name': '备稿演讲', 'sequence': 20, 'description': '准备好主题的正式演讲'},
                {'name': '即兴演讲', 'sequence': 30, 'description': '即兴话题演讲'},
                {'name': '点评', 'sequence': 40, 'description': '对演讲者的点评'},
            ]
            
            created_count = 0
            skipped_count = 0
            
            for cat_data in categories:
                # 检查是否已存在
                existing = request.env['item.role.category'].sudo().search([('name', '=', cat_data['name'])], limit=1)
                if not existing:
                    request.env['item.role.category'].sudo().create(cat_data)
                    _logger.info(f'✅ 创建分类: {cat_data["name"]}')
                    created_count += 1
                else:
                    _logger.info(f'⚠️  分类已存在: {cat_data["name"]}')
                    skipped_count += 1
            
            message = f'成功创建 {created_count} 个分类'
            if skipped_count > 0:
                message += f'，{skipped_count} 个已存在'
            
            return request.make_json_response(api_response(True, {
                'created': created_count,
                'skipped': skipped_count
            }, message=message))
            
        except Exception as e:
            _logger.error(f'❌ 创建默认分类失败: {str(e)}', exc_info=True)
            return request.make_json_response(api_response(False, message=f'创建失败: {str(e)}'))
    
    @http.route('/api/v1/activities/<int:activity_id>/items', type='http', auth='public', methods=['GET'], csrf=False, cors='*')
    def get_activity_items(self, activity_id, **kwargs):
        """获取会议的所有报名项目"""
        try:
            _logger.info(f'🔍 GET /activities/{activity_id}/items')
            
            # 获取活动
            activity = request.env['speech.activity'].sudo().browse(activity_id)
            
            if not activity.exists():
                _logger.warning(f'⚠️ 会议不存在: id={activity_id}')
                return request.make_json_response(api_response(False, message='会议不存在', code=404))
            
            # 获取所有报名项目
            items = request.env['activity.registration.item'].sudo().search([
                ('activity_id', '=', activity_id)
            ], order='sequence')
            
            _logger.info(f'📊 找到 {len(items)} 个报名项目')
            
            # 获取当前用户（如果已登录）
            current_user_id = None
            token = request.httprequest.headers.get('Authorization', '').replace('Bearer ', '')
            if token:
                user = request.env['wechat.user'].sudo().search([('token', '=', token)], limit=1)
                if user and user.check_token(token):
                    current_user_id = user.id
            
            # 检查报名时间
            from odoo import fields as odoo_fields
            now = odoo_fields.Datetime.now()
            registration_open = activity.registration_start_time <= now <= activity.registration_end_time
            
            result_items = []
            for item in items:
                # 获取报名记录
                registrations = []
                user_registration_id = None
                for reg in item.item_registration_ids:
                    registrations.append({
                        'id': reg.id,
                        'name': reg.name,
                        'introduction': reg.introduction,
                        'photo_url': reg.photo_url,
                        'speech_intro': reg.speech_intro,
                        'status': reg.status,
                        'user_id': reg.user_id.id,
                        'created_at': reg.create_date.strftime('%Y-%m-%d %H:%M:%S') if reg.create_date else '',
                    })
                    # 记录当前用户的报名ID（用于取消报名）
                    if current_user_id and reg.user_id.id == current_user_id:
                        user_registration_id = reg.id
                
                # 检查当前用户是否已报名
                user_registered = user_registration_id is not None
                
                # 检查是否已满员
                is_full = item.max_registrations > 0 and item.registration_count >= item.max_registrations
                
                result_items.append({
                    'id': item.id,
                    'name': item.name,
                    'sequence': item.sequence,
                    'description': item.description or '',
                    'registration_count': item.registration_count,
                    'max_registrations': item.max_registrations,
                    'is_full': is_full,
                    'registrations': registrations,
                    'user_registered': user_registered,
                    'user_registration_id': user_registration_id,  # 用于取消报名
                    'require_introduction': item.require_introduction,
                    'require_photo': item.require_photo,
                    'require_speech_intro': item.require_speech_intro,
                    # 角色分类信息
                    'role_category_id': item.role_category_id.id if item.role_category_id else None,
                    'role_category_name': item.role_category_id.name if item.role_category_id else '',
                })
            
            # 返回报名时间状态
            return request.make_json_response(api_response(True, {
                'items': result_items,
                'registration_open': registration_open,
                'registration_start_time': activity.registration_start_time.strftime('%Y-%m-%d %H:%M:%S') if activity.registration_start_time else '',
                'registration_end_time': activity.registration_end_time.strftime('%Y-%m-%d %H:%M:%S') if activity.registration_end_time else '',
            }))
            

            
        except Exception as e:
            _logger.error(f'❌ 获取报名项目失败: {str(e)}', exc_info=True)
            return request.make_json_response(api_response(False, message=f'获取失败: {str(e)}'))
    
    @http.route('/api/v1/activities/<int:activity_id>/items/<int:item_id>/register', type='http', auth='public', methods=['POST'], csrf=False, cors='*')
    def register_for_item(self, activity_id, item_id, **kwargs):
        """报名参加某个项目"""
        try:
            # 验证Token
            token = request.httprequest.headers.get('Authorization', '').replace('Bearer ', '')
            _logger.info(f'🔍 POST /activities/{activity_id}/items/{item_id}/register: token={token[:20] if token else "无"}...')
            
            if not token:
                _logger.warning('⚠️ 未提供Token')
                return request.make_json_response(api_response(False, message='请先登录', code=401))
            
            user = request.env['wechat.user'].sudo().search([('token', '=', token)], limit=1)
            
            if not user or not user.check_token(token):
                _logger.warning(f'⚠️ Token无效: {token[:20]}...')
                return request.make_json_response(api_response(False, message='登录已过期，请重新登录', code=401))
            
            _logger.info(f'💚 Token验证成功: 用户={user.name}')
            
            # 检查项目是否存在
            item = request.env['activity.registration.item'].sudo().browse(item_id)
            
            if not item.exists() or item.activity_id.id != activity_id:
                _logger.warning(f'⚠️ 报名项目不存在: item_id={item_id}, activity_id={activity_id}')
                return request.make_json_response(api_response(False, message='报名项目不存在', code=404))
            
            activity = item.activity_id
            
            # 1. 检查报名时间
            from datetime import datetime
            from odoo import fields as odoo_fields
            now = odoo_fields.Datetime.now()
            
            if now < activity.registration_start_time:
                _logger.warning(f'⚠️ 报名尚未开始: now={now}, start={activity.registration_start_time}')
                return request.make_json_response(api_response(False, message='报名尚未开始'))
            
            if now > activity.registration_end_time:
                _logger.warning(f'⚠️ 报名已结束: now={now}, end={activity.registration_end_time}')
                return request.make_json_response(api_response(False, message='报名已结束'))
            
            # 2. 检查是否已报名
            existing = request.env['activity.item.registration'].sudo().search([
                ('item_id', '=', item_id),
                ('user_id', '=', user.id)
            ], limit=1)
            
            if existing:
                _logger.warning('⚠️ 用户已报名此项目')
                return request.make_json_response(api_response(False, message='您已经报名过此项目'))
            
            # 3. 检查最大报名人数
            if item.max_registrations > 0 and item.registration_count >= item.max_registrations:
                _logger.warning(f'⚠️ 报名人数已满: count={item.registration_count}, max={item.max_registrations}')
                return request.make_json_response(api_response(False, message=f'该项目报名人数已满（最多{item.max_registrations}人）'))
            
            # 从Body读取数据
            import json
            body_data = request.httprequest.get_data(as_text=True)
            data = json.loads(body_data) if body_data else {}
            
            _logger.info(f'📝 项目报名: name={data.get("name")}, item={item.name}')
            
            # 4. 验证必填项
            if not data.get('name') or not data.get('name').strip():
                return request.make_json_response(api_response(False, message='姓名不能为空'))
            
            if item.require_introduction and (not data.get('introduction') or not data.get('introduction').strip()):
                return request.make_json_response(api_response(False, message='自我介绍不能为空'))
            
            if item.require_photo and not data.get('photo_url'):
                return request.make_json_response(api_response(False, message='个人照片不能为空'))
            
            if item.require_speech_intro and (not data.get('speech_intro') or not data.get('speech_intro').strip()):
                return request.make_json_response(api_response(False, message='演讲介绍不能为空'))
            
            # 创建报名记录
            registration = request.env['activity.item.registration'].sudo().create({
                'item_id': item_id,
                'user_id': user.id,
                'name': data.get('name'),
                'introduction': data.get('introduction', ''),
                'photo_url': data.get('photo_url', ''),
                'speech_intro': data.get('speech_intro', ''),
                'status': 'approved',  # 默认自动通过
            })
            
            _logger.info(f'✅ 报名成功: id={registration.id}, item={item.name}, user={user.name}')
            
            return request.make_json_response(api_response(True, {'id': registration.id}, '报名成功'))
            
        except Exception as e:
            _logger.error(f'❌ 项目报名失败: {str(e)}', exc_info=True)
            return request.make_json_response(api_response(False, message=f'报名失败: {str(e)}'))
    
    @http.route('/api/v1/activities/<int:activity_id>/items/<int:item_id>/registrations', type='http', auth='public', methods=['GET'], csrf=False, cors='*')
    def get_item_registrations(self, activity_id, item_id, **kwargs):
        """获取某个项目的所有报名记录（仅管理员）"""
        try:
            # 验证Token
            token = request.httprequest.headers.get('Authorization', '').replace('Bearer ', '')
            _logger.info(f'🔍 GET /activities/{activity_id}/items/{item_id}/registrations')
            
            if not token:
                return request.make_json_response(api_response(False, message='请先登录', code=401))
            
            user = request.env['wechat.user'].sudo().search([('token', '=', token)], limit=1)
            
            if not user or not user.check_token(token):
                return request.make_json_response(api_response(False, message='登录已过期', code=401))
            
            # 检查是否是会议管理员
            activity = request.env['speech.activity'].sudo().browse(activity_id)
            if not activity.exists():
                return request.make_json_response(api_response(False, message='会议不存在', code=404))
            
            # 检查用户是否是管理员或创建者
            is_manager = user.id == activity.creator_id.id or user in activity.manager_ids
            if not is_manager:
                return request.make_json_response(api_response(False, message='无权限查看报名列表', code=403))
            
            # 获取该项目的所有报名记录
            item = request.env['activity.registration.item'].sudo().browse(item_id)
            if not item.exists() or item.activity_id.id != activity_id:
                return request.make_json_response(api_response(False, message='报名项目不存在', code=404))
            
            registrations = request.env['activity.item.registration'].sudo().search([
                ('item_id', '=', item_id)
            ], order='create_date desc')
            
            result = []
            for reg in registrations:
                result.append({
                    'id': reg.id,
                    'name': reg.name,
                    'introduction': reg.introduction or '',
                    'photo_url': reg.photo_url or '',
                    'speech_intro': reg.speech_intro or '',
                    'status': reg.status,
                    'create_date': reg.create_date.strftime('%Y-%m-%d %H:%M:%S') if reg.create_date else '',
                    'user_name': reg.user_id.name if reg.user_id else '未知用户'
                })
            
            _logger.info(f'✅ 返回 {len(result)} 条报名记录')
            return request.make_json_response(api_response(True, {'registrations': result}))
            
        except Exception as e:
            _logger.error(f'❌ 获取报名列表失败: {str(e)}', exc_info=True)
            return request.make_json_response(api_response(False, message=f'获取失败: {str(e)}'))
    
    @http.route('/api/v1/activities/<int:activity_id>/items/<int:item_id>/register/<int:registration_id>', type='http', auth='public', methods=['DELETE'], csrf=False, cors='*')
    def cancel_registration(self, activity_id, item_id, registration_id, **kwargs):
        """取消报名"""
        try:
            # 验证Token
            token = request.httprequest.headers.get('Authorization', '').replace('Bearer ', '')
            _logger.info(f'🔍 DELETE /activities/{activity_id}/items/{item_id}/register/{registration_id}: token={token[:20] if token else "无"}...')
            
            if not token:
                _logger.warning('⚠️ 未提供Token')
                return request.make_json_response(api_response(False, message='请先登录', code=401))
            
            user = request.env['wechat.user'].sudo().search([('token', '=', token)], limit=1)
            
            if not user or not user.check_token(token):
                _logger.warning(f'⚠️ Token无效: {token[:20]}...')
                return request.make_json_response(api_response(False, message='登录已过期，请重新登录', code=401))
            
            _logger.info(f'💚 Token验证成功: 用户={user.name}')
            
            # 检查报名记录是否存在
            registration = request.env['activity.item.registration'].sudo().browse(registration_id)
            
            if not registration.exists():
                _logger.warning(f'⚠️ 报名记录不存在: registration_id={registration_id}')
                return request.make_json_response(api_response(False, message='报名记录不存在', code=404))
            
            if registration.item_id.id != item_id or registration.activity_id.id != activity_id:
                _logger.warning(f'⚠️ 报名记录不匹配')
                return request.make_json_response(api_response(False, message='报名记录不匹配', code=400))
            
            activity = registration.activity_id
            
            # 检查权限：只有报名用户自己或会议创建者/管理员可以取消
            can_cancel = False
            if registration.user_id.id == user.id:
                can_cancel = True
                _logger.info(f'✅ 用户自己取消报名')
            elif activity.creator_id.id == user.id:
                can_cancel = True
                _logger.info(f'✅ 会议创建者取消报名')
            elif user.id in activity.manager_ids.ids:
                can_cancel = True
                _logger.info(f'✅ 会议管理员取消报名')
            
            if not can_cancel:
                _logger.warning(f'⚠️ 无权限取消报名: user_id={user.id}, registration_user_id={registration.user_id.id}')
                return request.make_json_response(api_response(False, message='无权限取消此报名', code=403))
            
            # 删除报名记录
            registration.sudo().unlink()
            
            _logger.info(f'✅ 取消报名成功: registration_id={registration_id}')
            
            return request.make_json_response(api_response(True, {}, '取消报名成功'))
            
        except Exception as e:
            _logger.error(f'❌ 取消报名失败: {str(e)}', exc_info=True)
            return request.make_json_response(api_response(False, message=f'取消报名失败: {str(e)}'))
    
    @http.route('/api/v1/activities/<int:activity_id>/items/create', type='http', auth='public', methods=['POST'], csrf=False, cors='*')
    def create_item(self, activity_id, **kwargs):
        """创建新的报名项目（仅会议管理员）"""
        try:
            # 验证Token
            token = request.httprequest.headers.get('Authorization', '').replace('Bearer ', '')
            _logger.info(f'🔍 POST /activities/{activity_id}/items/create: token={token[:20] if token else "无"}...')
            
            if not token:
                _logger.warning('⚠️ 未提供Token')
                return request.make_json_response(api_response(False, message='请先登录', code=401))
            
            user = request.env['wechat.user'].sudo().search([('token', '=', token)], limit=1)
            
            if not user or not user.check_token(token):
                _logger.warning(f'⚠️ Token无效: {token[:20]}...')
                return request.make_json_response(api_response(False, message='登录已过期，请重新登录', code=401))
            
            _logger.info(f'💚 Token验证成功: 用户={user.name}')
            
            # 检查是否有管理权限
            activity = request.env['speech.activity'].sudo().browse(activity_id)
            
            if not activity.exists():
                _logger.warning(f'⚠️ 会议不存在: activity_id={activity_id}')
                return request.make_json_response(api_response(False, message='会议不存在', code=404))
            
            if not activity.can_user_manage(user):
                _logger.warning(f'⚠️ 无权限管理此会议: user={user.name}')
                return request.make_json_response(api_response(False, message='您没有权限管理此会议', code=403))
            
            # 从Body读取数据
            import json
            body_data = request.httprequest.get_data(as_text=True)
            data = json.loads(body_data) if body_data else {}
            
            name = data.get('name')
            if not name:
                return request.make_json_response(api_response(False, message='项目名称不能为空'))
            
            # 获取sequence（可以由前端指定，用于插入操作）
            sequence = data.get('sequence')
            
            if sequence is None:
                # 如果没有指定sequence，获取当前最大序号+1
                max_seq = request.env['activity.registration.item'].sudo().search([
                    ('activity_id', '=', activity_id)
                ], order='sequence desc', limit=1)
                
                sequence = (max_seq.sequence + 1) if max_seq else 1
            
            _logger.info(f'📝 创建项目: name={name}, sequence={sequence}')
            
            # 准备创建数据
            create_vals = {
                'name': name,
                'sequence': sequence,
                'activity_id': activity_id,
                'description': data.get('description', ''),
            }
            
            # 如果前端提供了角色分类，使用它
            if data.get('role_category_id'):
                create_vals['role_category_id'] = int(data.get('role_category_id'))
                _logger.info(f'📁 指定角色分类: {create_vals["role_category_id"]}')
            
            # 创建项目
            item = request.env['activity.registration.item'].sudo().create(create_vals)
            
            _logger.info(f'✅ 项目创建成功: id={item.id}, name={item.name}')
            
            return request.make_json_response(api_response(True, {'id': item.id, 'name': item.name, 'sequence': item.sequence}, '创建成功'))
            
        except Exception as e:
            _logger.error(f'❌ 创建项目失败: {str(e)}', exc_info=True)
            return request.make_json_response(api_response(False, message=f'创建失败: {str(e)}'))
    
    @http.route('/api/v1/activities/<int:activity_id>/items/<int:item_id>', type='http', auth='public', methods=['PUT', 'DELETE'], csrf=False, cors='*')
    def manage_item(self, activity_id, item_id, **kwargs):
        """更新或删除报名项目（仅会议管理员）"""
        try:
            # 验证Token
            token = request.httprequest.headers.get('Authorization', '').replace('Bearer ', '')
            _logger.info(f'🔍 {request.httprequest.method} /activities/{activity_id}/items/{item_id}: token={token[:20] if token else "无"}...')
            
            if not token:
                _logger.warning('⚠️ 未提供Token')
                return request.make_json_response(api_response(False, message='请先登录', code=401))
            
            user = request.env['wechat.user'].sudo().search([('token', '=', token)], limit=1)
            
            if not user or not user.check_token(token):
                _logger.warning(f'⚠️ Token无效: {token[:20]}...')
                return request.make_json_response(api_response(False, message='登录已过期，请重新登录', code=401))
            
            _logger.info(f'💚 Token验证成功: 用户={user.name}')
            
            # 检查是否有管理权限
            activity = request.env['speech.activity'].sudo().browse(activity_id)
            
            if not activity.exists():
                _logger.warning(f'⚠️ 会议不存在: activity_id={activity_id}')
                return request.make_json_response(api_response(False, message='会议不存在', code=404))
            
            if not activity.can_user_manage(user):
                _logger.warning(f'⚠️ 无权限管理此会议: user={user.name}')
                return request.make_json_response(api_response(False, message='您没有权限管理此会议', code=403))
            
            # 检查项目是否存在
            item = request.env['activity.registration.item'].sudo().browse(item_id)
            
            if not item.exists() or item.activity_id.id != activity_id:
                _logger.warning(f'⚠️ 报名项目不存在: item_id={item_id}')
                return request.make_json_response(api_response(False, message='报名项目不存在', code=404))
            
            if request.httprequest.method == 'PUT':
                # 更新项目
                import json
                body_data = request.httprequest.get_data(as_text=True)
                data = json.loads(body_data) if body_data else {}
                
                _logger.info(f'📝 收到更新数据: {data}')
                
                update_vals = {}
                if data.get('name'):
                    update_vals['name'] = data.get('name')
                if 'description' in data:
                    update_vals['description'] = data.get('description', '')
                if 'sequence' in data:
                    update_vals['sequence'] = int(data.get('sequence'))
                
                # 更新角色分类
                if 'role_category_id' in data and data.get('role_category_id'):
                    update_vals['role_category_id'] = int(data.get('role_category_id'))
                
                # 更新配置字段
                if 'max_registrations' in data:
                    update_vals['max_registrations'] = int(data.get('max_registrations', 0))
                if 'require_introduction' in data:
                    update_vals['require_introduction'] = bool(data.get('require_introduction'))
                if 'require_photo' in data:
                    update_vals['require_photo'] = bool(data.get('require_photo'))
                if 'require_speech_intro' in data:
                    update_vals['require_speech_intro'] = bool(data.get('require_speech_intro'))
                
                _logger.info(f'📝 更新项目: item_id={item_id}, vals={update_vals}')
                
                item.sudo().write(update_vals)
                
                _logger.info(f'✅ 项目更新成功')
                
                return request.make_json_response(api_response(True, message='更新成功'))
            
            elif request.httprequest.method == 'DELETE':
                # 删除项目（需要检查是否已有人报名）
                if len(item.item_registration_ids) > 0:
                    _logger.warning(f'⚠️ 项目已有人报名，不能删除: item_id={item_id}')
                    return request.make_json_response(api_response(False, message='该项目已有人报名，不能删除'))
                
                _logger.info(f'🗑️ 删除项目: item_id={item_id}, name={item.name}')
                
                item.sudo().unlink()
                
                _logger.info(f'✅ 项目删除成功')
                
                return request.make_json_response(api_response(True, message='删除成功'))
            
        except Exception as e:
            _logger.error(f'❌ 项目管理失败: {str(e)}', exc_info=True)
            return request.make_json_response(api_response(False, message=f'操作失败: {str(e)}'))
    
    @http.route('/api/v1/registrations/<int:registration_id>/performance-photo', type='http', auth='public', methods=['POST'], csrf=False, cors='*')
    def upload_performance_photo(self, registration_id, **kwargs):
        """上传演讲风采照片（仅管理员）"""
        try:
            # 验证Token
            token = request.httprequest.headers.get('Authorization', '').replace('Bearer ', '')
            _logger.info(f'📷 POST /registrations/{registration_id}/performance-photo')
            
            if not token:
                return request.make_json_response(api_response(False, message='请先登录', code=401))
            
            user = request.env['wechat.user'].sudo().search([('token', '=', token)], limit=1)
            
            if not user or not user.check_token(token):
                return request.make_json_response(api_response(False, message='登录已过期，请重新登录', code=401))
            
            # 获取报名记录
            registration = request.env['activity.item.registration'].sudo().browse(registration_id)
            
            if not registration.exists():
                return request.make_json_response(api_response(False, message='报名记录不存在', code=404))
            
            # 检查是否是会议管理员或创建者
            activity = registration.activity_id
            is_manager = user.id == activity.creator_id.id or user in activity.manager_ids
            
            if not is_manager:
                return request.make_json_response(api_response(False, message='权限不足，仅管理员可上传', code=403))
            
            # 获取上传的文件
            if 'file' not in request.httprequest.files:
                return request.make_json_response(api_response(False, message='请选择要上传的文件'))
            
            file = request.httprequest.files['file']
            
            if file.filename == '':
                return request.make_json_response(api_response(False, message='文件名不能为空'))
            
            # 检查文件类型
            import os
            filename = file.filename
            file_ext = os.path.splitext(filename)[1].lower()
            allowed_exts = ['.jpg', '.jpeg', '.png', '.gif']
            
            if file_ext not in allowed_exts:
                return request.make_json_response(api_response(False, message=f'不支持的文件类型'))
            
            # 生成新的文件名
            import time
            new_filename = f'performance_{registration.id}_{int(time.time())}{file_ext}'
            
            # 保存文件到Odoo附件
            import base64
            file_content = file.read()
            
            attachment = request.env['ir.attachment'].sudo().create({
                'name': new_filename,
                'datas': base64.b64encode(file_content),
                'res_model': 'activity.item.registration',
                'res_id': registration.id,
                'public': True,
                'type': 'binary',
            })
            
            # 生成访问URL（使用固定的外部域名）
            photo_url = f'https://naturedao.tech/web/content/{attachment.id}?download=true'
            
            # 更新报名记录的演讲风采照片（追加到现有照片列表）
            existing_urls = registration.performance_photo_urls or ''
            if existing_urls:
                new_urls = existing_urls + ',' + photo_url
            else:
                new_urls = photo_url
            
            registration.sudo().write({'performance_photo_urls': new_urls})
            
            _logger.info(f'✅ 风采照片上传成功: url={photo_url}, total={len(new_urls.split(","))}')
            
            return request.make_json_response(api_response(True, {
                'photo_url': photo_url,
                'all_photo_urls': new_urls.split(','),
                'attachment_id': attachment.id
            }, '上传成功'))
            
        except Exception as e:
            _logger.error(f'❌ 上传风采照片失败: {str(e)}', exc_info=True)
            return request.make_json_response(api_response(False, message=f'上传失败: {str(e)}'))
    
    @http.route('/api/v1/user/registrations', type='http', auth='public', methods=['GET'], csrf=False, cors='*')
    def user_registrations(self, **kwargs):
        """获取当前用户的所有报名记录"""
        try:
            # 验证Token
            token = request.httprequest.headers.get('Authorization', '').replace('Bearer ', '')
            _logger.info(f'🔍 GET /user/registrations: token={token[:20] if token else "无"}...')
            
            if not token:
                _logger.warning('⚠️ 未提供Token')
                return request.make_json_response(api_response(False, message='请先登录', code=401))
            
            user = request.env['wechat.user'].sudo().search([('token', '=', token)], limit=1)
            
            if not user or not user.check_token(token):
                _logger.warning(f'⚠️ Token无效: {token[:20]}...')
                return request.make_json_response(api_response(False, message='登录已过期，请重新登录', code=401))
            
            _logger.info(f'💚 Token验证成功: 用户={user.name}, user_id={user.id}')
            
            # 获取用户的所有报名记录
            registrations = request.env['activity.item.registration'].sudo().search([
                ('user_id', '=', user.id)
            ], order='create_date desc')
            
            _logger.info(f'📊 查询报名记录: user_id={user.id}, 找到 {len(registrations)} 条')
            
            # 如果没有找到，输出详细调试信息
            if len(registrations) == 0:
                all_regs = request.env['activity.item.registration'].sudo().search([], limit=5)
                _logger.info(f'🔍 数据库中最近的5条报名记录:')
                for reg in all_regs:
                    _logger.info(f'   - id={reg.id}, user_id={reg.user_id.id}, name={reg.name}, item={reg.item_id.name}')
            
            items = []
            for reg in registrations:
                activity = reg.activity_id
                items.append({
                    'id': reg.id,
                    'activity_id': activity.id,
                    'activity_title': activity.title,
                    'activity_start_time': activity.start_time.strftime('%Y-%m-%d %H:%M') if activity.start_time else '',
                    'activity_status': activity.status,
                    'item_id': reg.item_id.id,
                    'item_name': reg.item_id.name,
                    'name': reg.name,
                    'introduction': reg.introduction,
                    'photo_url': reg.photo_url,
                    'speech_intro': reg.speech_intro,
                    'status': reg.status,
                    'created_at': reg.create_date.strftime('%Y-%m-%d %H:%M:%S') if reg.create_date else '',
                })
            
            _logger.info(f'✅ 返回 {len(items)} 条报名数据')
            
            return request.make_json_response(api_response(True, {'items': items, 'total': len(items)}))
            
        except Exception as e:
            _logger.error(f'❌ 获取用户报名失败: {str(e)}', exc_info=True)
            return request.make_json_response(api_response(False, message=f'获取失败: {str(e)}'))

